#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import sys
import re
import os

import logging
from logging.handlers import RotatingFileHandler
'''
--------------Logger------------------------------
-------------/-1---\--1---------------------------
-----------/---------\----------------------------
---------/-------------\--------------------------
-------/-n---------------\--n---------------------
----Filter <-1-------1--Handler-------------------
-------------------------|------------------------
-------------------------|------------------------
-------------------------|------------------------
---------------------Formatter--------------------
'''

'''
%(levelno)s	    打印日志级别的数值
%(levelname)s	打印日志级别名称
%(pathname)s	打印当前执行程序的路径
%(filename)s	打印当前执行程序名称
%(funcName)s	打印日志的当前函数
%(lineno)d	    打印日志的当前行号
%(asctime)s	    打印日志的时间
%(thread)d	    打印线程id
%(threadName)s	打印线程名称
%(process)d	    打印进程ID
%(message)s	    打印日志信息
'''
'''
* classname    : stringFilter 继承logging.Filter
* para()       :
* return       : 
* discription  : 重写logging.Filter类中的filter()方法，对日志进行过滤
* author       : zhongmingsen
* date         : 2023-06-14 
'''
class stringFilter(logging.Filter):
    def filter(self, record):
        if record.msg.find('cons') == -1:
            return True
        return False
'''
* classname    : levelFilter 继承logging.Filter
* para()       :
* return       : 
* discription  : 重写logging.Filter类中的filter()方法，对日志进行过滤
* author       : zhongmingsen
* date         : 2023-06-14 
'''    
class levelFilter(logging.Filter): 
    def filter(self, record):
        if record.levelno > logging.WARNING:
            return True
        return False

'''
* functionname : loggerCfgConsoleHandler
* para()       :
* return       : logger handler
* discription  : return Rotating file handler
* author       : zhongmingsen
* date         : 2023-06-14 
'''
def loggerCfgConsoleHandler() :
    try :
        # 创建一个日志器logger并设置其日志级别为DEBUG
        logger = logging.getLogger('console')
        logger.setLevel(logging.DEBUG)
        
        # 创建一个流处理器handler并设置其日志级别为DEBUG
        handler = logging.StreamHandler(sys.stdout)
        handler.setLevel(logging.DEBUG)

        #logging_filter = logging.Filter()        
        #logging_filter.filter = lambda record: record.levelno > logging.WARNING
        #logging_filter.filter = lambda record1: record1.msg.find('console1') == -1
     
        # 创建一个格式器formatter并将其添加到处理器handler
        formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s")
        handler.setFormatter(formatter)

        #handler.addFilter(levelFilter())
        # 为日志器logger添加上面创建的处理器handler
        logger.addHandler(handler)
        return logger
    except :
        print("loggerCfgConsoleHandler error")
'''
* functionname : loggerCfgFileHandler
* para()       :
* return       : logger handler
* discription  : return Rotating file handler
* author       : zhongmingsen
* date         : 2023-06-14 
'''
def loggerCfgFileHandler() :
    try :
        logger = logging.getLogger('file')
        logger.setLevel(logging.DEBUG)

        #fileHandler = logging.FileHandler('test.log')
        fileHandler = RotatingFileHandler("logging.log", maxBytes=1024 * 1, backupCount=3, encoding='utf-8')
        fileHandler.setLevel(logging.DEBUG)

        # 创建一个格式器formatter并将其添加到处理器handler
        formatter = logging.Formatter(
            fmt='%(asctime)s - %(name)s - %(levelname)s: - %(message)s',
            datefmt='%Y-%m-%d %H:%M:%S')
        fileHandler.setFormatter(formatter)
        # 给logger添加handler
        logger.addHandler(fileHandler)
        return logger
    except :
        print("loggerCfgFileHandler error")

'''
* functionname : loggerCfgFileAndConsoleHandler
* para()       :
* return       : logger handler
* discription  : return Rotating file handler
* author       : zhongmingsen
* date         : 2023-06-14 
'''
def loggerCfgFileAndConsoleHandler() :
    try :
        logger = logging.getLogger('fileandconsole')
        #logger = logging.getLogger('root')
        logger.setLevel(logging.DEBUG)

        fileHandler = logging.FileHandler('test.log')
        #fileHandler = RotatingFileHandler("test.log", maxBytes=1024 * 1, backupCount=0, encoding='utf-8')
        fileHandler.setLevel(logging.DEBUG)

        # 创建一个格式器formatter并将其添加到处理器handler
        formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s")
        fileHandler.setFormatter(formatter)

        consoleHandler = logging.StreamHandler()
        consoleHandler.setLevel(logging.DEBUG)

        # 创建一个格式器formatter并将其添加到处理器handler
        formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s")
        consoleHandler.setFormatter(formatter)
        # 给logger添加handler
        logger.addHandler(fileHandler)
        logger.addHandler(consoleHandler)
        return logger
    except :
        print("loggerCfgFileAndConsoleHandler error")

#------------------------------------------------------
#----------------------以下是测试code--------------------
#------------------------------------------------------

'''
* functionname : logger_test
* para()       :
* return       : 
* discription  : 
* author       : zhongmingsen
* date         : 2023-06-14 
'''
def logger_test(): 
    loggerc = loggerCfgConsoleHandler()
    loggerf = loggerCfgFileHandler()
    loggerfc = loggerCfgFileAndConsoleHandler()
    try :
        for i in range(500):
            #loggerc.info("console--%d", i)
            #loggerf.info("file--%d",i)
            loggerfc.info("fileandconsole--%d", i)
    except :
        print ('------error--------------')

'''
* function name : main
* para()        : 
* return        : 
* description   : 用于测试
* author        : zhongmingsen
* date          : 2023.4.1
'''                          
def main(argv=None):
    if argv is None:
        argv = sys.argv
        if len(argv) < 1:
            print('please set dbc file name!')
        else:                                           
            logger_test()
            print('get dbc signal tabel success!')   

if __name__ == "__main__":
    sys.exit(main())
